/**
 * Created by Blink on 2017/10/20.
 * search btdigg for btorrent.
 */

const fetch = require("fetch").fetchUrl;
const Buffer = require("buffer").Buffer;

const filterType = {
    all: 1,
    video: 2,
    music: 3,
    book: 4,
    soft: 5,
    compress: 6,
    other: 7,
    image: 8,
    iso: 9
};

const sortType = {
    related: 0,     // 相关
    size: 1,        // 大小
    fileNum: 2,     // 文件数
    popularity: 3,  // 人气
};

const search = (param) => {
    if (typeof param === "string") {
        param = {
            keyword: param,
            type: filterType.all,
            sort: sortType.related,
            page: 1
        }
    }

    const tmp = new Buffer(param.keyword);
    param.keyword = tmp.toString("base64");
    param.keyword = param.keyword.replace('=', '');

    return new Promise((res, rej) => {
        fetch("http://btdigg.xyz/search/" + param.keyword + "/" + param.page + "/" + param.type + "/" + param.sort + ".html", (error, meta, body) => {
            if (error) rej(error);
            else {
                res(parseHtml(body.toString()))
            }
        });
    });
};

const parseHtml = (html) => {
    const $ = require("cheerio").load(html),
        $list = $('.list dl');

    let list = [];

    for (let i = 0;i < $list.length; i++) {
        const item = $($list.get(i));

        const children = item.children(),
            r = {
                name: removeTag($(children.get(0)).find('a').html()),
            }, $attr = $(children.get(1)).find('span');

        r.time = new Date($($attr.get(0)).children('b').text());
        r.size = $($attr.get(1)).children('b').text();
        r.fileNum = $($attr.get(2)).children('b').text();
        r.speed = $($attr.get(3)).children('b').text();
        r.popularity = $($attr.get(4)).children('b').text();
        r.magnet = $($attr.get(5)).children('a').attr('href');

        r.files = [];
        const $files = $(children.get(2)).children('p');

        for (let i = 0; i < $files.length; i++) {
            const item = $($files.get(i)),
                name = removeTag(item.find('.filename').html());

            let f = {
                name,
                size: item.find('.size').text(),
                postfix: postfixRegex.exec(name)
            };

            if (f.postfix) f.postfix = f.postfix[0].substr(1);
            r.files.push(f);
        }
        list.push(r);
    }

    const footer = $('.page-split');

    let info = $('.bar').text(),
        totalPage = parseInt($(footer.children().get(0)).text().replace(/[共页]/g, '')),
        currentPage = parseInt($(footer.children().get(1)).text());

    return {
        info,
        totalPage,
        currentPage,
        list
    }

    // return ret;
};

const regexTagB = /\<b\>|\<\/b\>/g;
const postfixRegex = /\.[^\.]+$/;
const removeTag = (s) => {
    return s.replace(regexTagB, '');
};

export {
    search,
    filterType,
    sortType
}